// pages/search/search.js
var config = require('../../script/config');
var orderApi = require('../../script/order.js');
var publicApi = require('../../script/public.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: 0,
    menuRight: 0,
    menuTop: 0,
    menuHeight: 0,
    type: 1, // 1、显示地址 2.显示工单
    userinfo: null,
    status: '',
    IsFinish: false,
    input_timeOut: null,
    addressList: [],
    pagination: {
      page: 1,
      rows: 4,
      sidx: '',
      sord: ''
    },
    addressList: [],
    showAddressList: [],
    showAddressListRick: [],
    selectedAddressIndex: 0,
    orderList: [],
    canLoadData: true,
  },
  _refreshData: function () {
    this.setData({ //初始化数据
      type: 1, // 1、显示地址 2.显示工单
      userinfo: null,
      addressList: [],
      pagination: {
        page: 1,
        rows: 4,
        sidx: '',
        sord: ''
      },
      addressList: [],
      showAddressList: [],
      showAddressListRick: [],
      noShowAddress: false,
      selectedAddressIndex: 0,
      orderList: [],
      noOrder: false,
      canLoadData: true,
      noOrder: false,
      noShowAddress: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.status) {
      this.setData({
        status: options.status
      })
    }
    if (options.IsFinish) {
      this.setData({
        IsFinish: options.IsFinish == '1'
      })
    }
    const that = this;
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    // 胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    // 导航栏高度 = 状态栏高度 + 44
    that.setData({
      navBarHeight: systemInfo.statusBarHeight + 44,
      menuRight: systemInfo.screenWidth - menuButtonInfo.right,
      menuTop: menuButtonInfo.top,
      menuHeight: menuButtonInfo.height
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this._refreshData()
    this.getUserInfo()
    this.searchAdderss()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.type === 1) return;
    if (this.data.canLoadData) {
      this.setData({
        'pagination.page': this.data.pagination.page + 1
      })
      this.getOrderList();
    } else {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none',
        duration: 1000
      });
    }
  },
  getUserInfo: function () {
    try {
      var value = wx.getStorageSync(config.storageKey.userinfo)
      if (value) {
        this.setData({
          userinfo: value
        })
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  back: function () {
    wx.navigateBack();
  },
  searchFocus: function (e) {
    this.setData({
      showDelete: true,
      type: 1,
      noOrder: false,
      noShowAddress: false
    })
  },
  searchBlur: function (e) {
    this.setData({
      showDelete: false
    })
  },
  searchChange: function (e) {
    let {
      input_timeOut
    } = this.data
    if (input_timeOut) {
      clearTimeout(input_timeOut)
    }
    input_timeOut = setTimeout(() => {
      this.filterAdderss(e.detail.value)
    }, 300);
    this.setData({
      input_timeOut
    }) // 计时器
  },
  filterAdderss(val) {
    if (val) {
      const showAddressList = []
      const showAddressListRick = []
      this.data.addressList.forEach(item => {
        const cur = this.markKeyWord(val, item)
        if (item.indexOf(val) > -1) {
          showAddressList.push(item)
          showAddressListRick.push(cur)
        }
      });
      this.setData({
        showAddressList: showAddressList,
        showAddressListRick: showAddressListRick,
        noShowAddress: showAddressListRick.length == 0
      })
    } else {
      this.setData({
        showAddressList: [],
        showAddressListRick: [],
        noShowAddress: true
      })
    }
  },
  markKeyWord(kw, str) {
    const reg = new RegExp(kw, 'ig')
    return str.replace(reg, function (match) {
      return `<span style="color:red">${match}</span>`
    })
  },
  searchAdderss() {
    const params = {
      WxStatus: this.data.status,
      IsFinish: this.data.IsFinish
    };
    orderApi.GetOrderAddressList(params).then(res => {
      if (res.code === 200) {
        this.setData({
          addressList: res.data,
          type: 1
        })
      }
    });
  },
  searchOrder(e) {
    this.setData({
      selectedAddressIndex: e.currentTarget.dataset.index,
      orderList: [],
      noOrder: false,
      canLoadData: true,
      type: 2
    })
    this.getOrderList()
  },
  getOrderList() {
    let params = {
      pagination: this.data.pagination,
      queryParam: {
        Address: this.data.showAddressList[this.data.selectedAddressIndex],
        WxStatus: this.data.status,
        IsFinish: this.data.IsFinish,
        NeedAudit: 0
      }
    };
    orderApi.GetOrderList(params).then(res => {
      if (res.code === 200) {
        let canLoadData = res.data.HasNextPages;
        const list = [...this.data.orderList, ...res.data.Items]
        this.setData({
          orderList: list,
          canLoadData: canLoadData,
          noOrder: list.length === 0
        })
      }
    });
  },
  todoOrder: function (e) {
    const WorkID = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "../do-order/do-order?WorkID=" + WorkID
    })
  },
  toPage(e) {
    const info = e.currentTarget.dataset.info;
    const WorkID = info.WorkID;
    if (info.NewStatus == '03' || info.NewStatus == '05') {
      wx.navigateTo({
        url: "../order-detail/order-detail?WorkID=" + WorkID
      })
    } else {
      wx.navigateTo({
        url: "../do-order/do-order?WorkID=" + WorkID
      })
    }
  },
  call: function (e) {
    var pnonenum = e.currentTarget.dataset.phone
    var res = wx.getSystemInfoSync();
    if (res.platform == 'ios') {
      wx.makePhoneCall({
        phoneNumber: pnonenum
      });
    } else {
      wx.showActionSheet({
        itemList: [pnonenum, '呼叫'],
        success: function (res) {
          console.log(res);
          if (res.tapIndex == 1) {
            wx.makePhoneCall({
              phoneNumber: pnonenum
            })
          }
        }
      })
    }
  },
  toMap(e) {
    var info = e.currentTarget.dataset.info
    wx.getLocation({
      type: 'gcj02', //返回可以用于 wx.openLocation 的经纬度
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        wx.openLocation({
          latitude,
          longitude,
          address: info.Address,
          scale: 18
        })
      }
    })
  },
})